package it.bd.SetAllConnectionsOff.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TabHost;

import it.bd.SetAllConnectionsOff.R;
import it.bd.SetAllConnectionsOff.ScreenListenerService;
import it.bd.SetAllConnectionsOff.SetAllConnectionsOff;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public class AdvancedTabActivity extends Activity {

    public static final String SCREENONOFF_PREF_NAME = "ScreenOnOff";
    private static Context     context;
    private Intent             serviceIntent;
    private SharedPreferences  pref;

    public AdvancedTabActivity() {
        super();
    }

    public AdvancedTabActivity(TabHost tabHost, Context context) {
        super();
        AdvancedTabActivity.context = context;
        attachOnTabHost(tabHost);
    }

    Context getContext() {
        return context;
    }

    String getIndicator() {
        return getContext().getString(R.string.advanced);
    }

    String getTabTag() {
        return "advanced";
    }

    public void attachOnTabHost(TabHost tabHost) {
        Intent i = new Intent(getContext(), this.getClass());
        tabHost.addTab(tabHost.newTabSpec(getTabTag()).setIndicator(getIndicator()).setContent(i));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.advanced);
        pref = getContext().getSharedPreferences(SetAllConnectionsOff.PREF_NAME, 0);
        serviceIntent = new Intent(this, ScreenListenerService.class);
        CheckBox screenBox = (CheckBox) findViewById(R.id.cbScreenWatch);

        refreshServiceStatus();

        screenBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // SAlvo le impostazioni
                Editor e = pref.edit();
                e.putBoolean(SCREENONOFF_PREF_NAME, isChecked);
                e.commit();
                if (isChecked) {
                    // Abilitato
                    startService(serviceIntent);
                } else {
                    stopService(serviceIntent);
                }
            }
        });
    }

    private void refreshServiceStatus() {
        boolean serviceStatus = pref.getBoolean(SCREENONOFF_PREF_NAME, false);

        CheckBox checkboxService = (CheckBox) findViewById(R.id.cbScreenWatch);
        checkboxService.setChecked(serviceStatus);
    }
}
